package com.hnxxxy.service.impl;

import com.hnxxxy.mapper.UserOperationMapper;
import com.hnxxxy.pojo.*;
import com.hnxxxy.service.UserOpertionservice;
import com.hnxxxy.system.aop.myLog.MyLog;
import com.hnxxxy.utils.Communal;
import net.sf.json.JSONObject;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserOpertionserviceImpl implements UserOpertionservice {
    private static final Logger log= LogManager.getLogger(UserOpertionserviceImpl.class);

    @Autowired
    UserOperationMapper userOperationMapper;

    @Autowired
    Communal communal;

    /**
     * 前台ajax登录请求的处理
     * @param username 学号
     * @param password 密码
     * @return 登录成功或失败的信息JSON
     */
    @Override
    @MyLog(value = "登录")
    public String ajaxLogin(String username, String password) {
        log.debug("执行UserOpertionserviceImpl的ajaxLogin");
        try {
            // 获取用户输入的信息
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            // 去UserRealm验证信息
            SecurityUtils.getSubject().login(token);
            // 获取user
            User_login user = (User_login) SecurityUtils.getSubject().getPrincipal();
            communal.setUser(user.getUsername());
            return communal.resultMap(200,   "登录成功");
        } catch (UnknownAccountException e) {
            return communal.resultMap(500,   "账号不存在！");
        }catch(IncorrectCredentialsException e1){
            return communal.resultMap(500,   "密码错误！");
        }catch (Exception e) {
            log.info(e);
            return communal.resultMap(500,   "其他错误");
        }
    }

    /**
     * 当前用户申请加入社团操作
     *
     * @param a_id 社团a_id
     * @return 操作成功或失败的json信息
     */
    @Override
    @MyLog(value = "申请加入社团")
    public String insertUserAssExa(int a_id) {
        log.debug("执行UserOpertionserviceImpl的insertUserAssExa");
        User_ass user_ass = new User_ass();
        user_ass.User_ass(communal.getUser(),a_id,0);
        return communal.RUD(userOperationMapper.insertUserAssExa(user_ass));
    }

    /**
     * 当前用户申请创建社团操作
     *
     * @param association 创建社团的信息
     * @return 操作成功或失败的json信息
     */
    @Override
    @MyLog(value = "申请创建社团")
    public String insertAss(Association association) {
        log.debug("执行UserOpertionserviceImpl的insertAss");
        association.setUsername(communal.getUser());
        String time;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        time = df.format(new Date());
        association.setCreationtime(time);
        association.setNumber(1);
        association.setExamine(0);
        return communal.RUD(userOperationMapper.insertAss(association));
    }

    /**
     * 放弃申请社团
     *
     * @param id user_ass 表id
     * @return 操作成功或失败的json信息
     */
    @Override
    @MyLog(value = "放弃申请社团")
    public String deleteUserAssExa(int id) {
        log.debug("执行UserOpertionserviceImpl的deleteUserAssExa");
        return communal.RUD(userOperationMapper.deleteUserAssExa(id));
    }

    /**
     * 修改或注册用户信息
     *
     * @param user 用户信息
     * @return 操作成功或失败的json信息
     */
    @Override
    @MyLog(value = "修改或注册用户信息,parameter=i注册，u修改")
    public String updateInsertUserInfo(User user,String password,String parameter) {
        log.debug("执行UserOpertionserviceImpl的updateUserInfo");
        try {
            if(parameter.equals("i")){
                log.debug("执行UserOpertionserviceImpl的注册");
                if (userOperationMapper.queryUserUsername(user.getUsername()) != null) {
                    return communal.resultMap(500, "学号已存在");
                }
                if (userOperationMapper.queryUserEmail(user.getEmail()) != null){
                    return communal.resultMap(500, "Email已存在");
                }
                int x = userOperationMapper.insertUser(user);

                User_login user_login = new User_login();
                String uuid = UUID.randomUUID().toString().toUpperCase();
                // 去掉-符号
                String salt = uuid.toString().replace("-", "");
                user_login.User_login(user.getUsername(),communal.md5(password,salt),salt);
                int y = userOperationMapper.insertUser_login(user_login);
                if(x > 0 && y > 0){
                    return communal.resultMap(200, "注册成功");
                }else {
                    return communal.resultMap(500, "注册失败");
                }
            }
            else if(parameter.equals("u")){
                log.debug("执行UserOpertionserviceImpl的修改");
                if (!userOperationMapper.queryUserUsername(user.getUsername()).getEmail().equals(user.getEmail())){
                    if (userOperationMapper.queryUserEmail(user.getEmail()) != null){
                        return communal.resultMap(500, "Email已存在");
                    }
                }
                return communal.RUD(userOperationMapper.updateUserInfo(user));
            }

            return communal.resultMap(500,   "其他错误");
        }catch (Exception e){
            log.info("执行UserOpertionserviceImpl的updateUserInfo异常："+e.toString());
            return communal.resultMap(500,   "其他错误");
        }
    }

    /**
     * 修改用户密码
     *
     * @param password 用户密码
     * @return 操作成功或失败的json信息
     */
    @Override
    @MyLog(value = "修改用户密码")
    public String updateUserPassword(String password) {
        log.debug("执行UserOpertionserviceImpl的updateUserPassword");
        String md5Password = communal.md5(password,userOperationMapper.queryUserSalt(communal.getUser()));
        return communal.RUD(userOperationMapper.updateUserPassword(md5Password));
    }

    /**
     * 查询用户权限
     * @return 用户权限信息
     */
    @Override
    public List<Jurisdiction> queryUserJur() {
        log.debug("执行UserOpertionserviceImpl的queryUserJur");
        List<Jurisdiction> list = userOperationMapper.queryUserJur(communal.getUser());
        for(int i = 0; i < list.size(); i++){
            for(int j = 0; j < list.size()-1-i;j++){
                if(list.get(j).getJ_id() > list.get(j+1).getJ_id()){
                    Jurisdiction jurisdiction = list.get(j);
                    list.set(j, list.get(j+1));
                    list.set(j+1,jurisdiction);
                }
            }
        }
        return list;
    }

    /**
     * 查询用户信息
     *
     * @return 用户信息
     */
    @Override
    public String queryUserInfo() {
        log.debug("执行UserOpertionserviceImpl的queryUserJur");
        Layui layui = new Layui();
        layui.Layui(0,"ok", (long) 1,userOperationMapper.queryUserInfo(communal.getUser()));
        return JSONObject.fromObject(layui).toString();
    }

    /**
     * 查询当前用户申请社团的审核信息
     *
     * @return 当前用户申请社团的审核信息
     */
    @Override
    public String queryUserAssExa(int page,int limit) {
        log.debug("执行UserOpertionserviceImpl的queryUserAssExa");
        return communal.runterListJson(page,limit,userOperationMapper.queryUserAssExa(communal.getUser()));
    }

    /**
     * 查询当前用户的角色
     *
     * @return 当前用户的角色
     */
    @Override
    public String queryUserRole() {
        log.debug("执行UserOpertionserviceImpl的queryUserRole");
        Layui layui = new Layui();
        layui.Layui(0,"ok", (long) 1,userOperationMapper.queryUserRole(communal.getUser()));
        return JSONObject.fromObject(layui).toString();
    }
}
